package com.yidi.system.service.imp;

import com.yidi.common.constant.UserConstants;
import com.yidi.common.core.domain.AjaxResult;
import com.yidi.common.core.domain.entity.SysRole;
import com.yidi.common.core.service.imp.AbstractBaseService;
import com.yidi.common.core.text.Convert;
import com.yidi.common.enums.RemoveEnum;
import com.yidi.common.utils.StringUtils;

import com.yidi.system.domain.SysPost;
import com.yidi.system.repository.SysPostRepository;
import com.yidi.system.repository.SysUserPostRepository;
import com.yidi.system.service.SysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：Xn
 * @ClassName: SysPostServiceImpl
 * @date ：2021-10-19 14:17
 * @describe ：
 */
@Service
public class SysPostServiceImpl extends AbstractBaseService<SysPost> implements SysPostService {

    @Autowired
    private SysPostRepository sysPostRepository;
    @Autowired
    private SysUserPostRepository sysUserPostRepository;
    @PersistenceContext
    private EntityManager em;

    /**
     * 分页
     */
    @Override
    public Page<SysPost> findByPage(Integer pageNo, Integer pageSize, SysPost post) {
        List<Sort.Order> orders = new ArrayList<>();
        orders.add(new Sort.Order(Sort.Direction.ASC, "orderNum"));
        Sort sort = Sort.by(orders);
        Pageable pageable = PageRequest.of(pageNo, pageSize, sort);

        Page<SysPost> page = sysPostRepository.findAll((root, query, cb) ->{
            List<Predicate> list = new ArrayList<>();
            list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));

            if(StringUtils.isNotBlank(post.getPostCode())) {
                list.add(cb.and(cb.like(root.get("postCode").as(String.class), post.getPostCode())));
            }

            if(StringUtils.isNotBlank(post.getStatus())) {
                list.add(cb.and(cb.equal(root.get("status").as(String.class), post.getStatus())));
            }

            if(StringUtils.isNotBlank(post.getPostName())) {
                list.add(cb.and(cb.like(root.get("postName").as(String.class), post.getPostName())));
            }

            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        },pageable);

        return page;
    }

    /**
     * 校验岗位名称是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostNameUnique(SysPost post)
    {
        Long postId = StringUtils.isNull(post.getId()) ? -1L : post.getId();
        SysPost info = sysPostRepository.findByPostName(post.getPostName());

        if (StringUtils.isNotNull(info) && !info.getId().equals(postId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验岗位编码是否唯一
     *
     * @param post 岗位信息
     * @return 结果
     */
    @Override
    public String checkPostCodeUnique(SysPost post)
    {
        Long postId = StringUtils.isNull(post.getId()) ? -1L : post.getId();
        SysPost info = sysPostRepository.findByPostCode(post.getPostCode());
        if (StringUtils.isNotNull(info) && !info.getId().equals(postId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public void updatePost(SysPost post) {
        SysPost p = findById(post.getId());
        p.setPostName(post.getPostName());
        p.setPostCode(post.getPostCode());
        p.setOrderNum(post.getOrderNum());
        p.setStatus(post.getStatus());
        p.setRemark(post.getRemark());

        modify(p);
    }

    /**
     * 批量删除岗位信息
     * (物理删除）
     * @param ids 需要删除的数据ID
     * @throws Exception
     */
    @Override
    public AjaxResult deletePostByIds(Long[] ids)
    {
        for (Long postId : ids)
        {
            SysPost post = findById(postId);
            if (countUserPostById(postId) > 0)
            {
                return AjaxResult.error( post.getPostName() + "已分配,不能删除");
            }
        }

        for(Long pId : ids) {
            delete(pId);
        }

        return AjaxResult.success();
    }

    /**
     * 通过岗位ID查询岗位使用数量
     *
     * @param postId 岗位ID
     * @return 结果
     */
    @Override
    public Integer countUserPostById(Long postId)
    {
        return sysUserPostRepository.countUserPostById(postId);
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId 用户ID
     * @return 选中岗位ID列表
     */
    @Override
    public List<Long> selectPostListByUserId(Long userId)
    {
        return sysPostRepository.selectPostListByUserId(userId);
    }

    /**
     * 查询用户所属岗位组
     *
     * @param userName 用户名
     * @return 结果
     */
    @Override
    public List<SysPost> selectPostsByUserName(String userName) {
        StringBuilder sql = new StringBuilder(
                "select p.id, p.post_name, p.post_code from sys_post p" +
                        " left join sys_user_post up on up.post_id = p.id" +
                        " left join sys_user u on u.id = up.user_id");

        if(StringUtils.isNotBlank(userName)){
            sql.append(" where u.user_name = '").append(userName).append("'");
        }

        Query query = em.createNativeQuery(sql.toString());
        List<Object[]> list = query.getResultList();
        List<SysPost> postList = new ArrayList<SysPost>();
        for(Object[] objects : list){
            SysPost sp = new SysPost();
            sp.setId(Long.valueOf(objects[0].toString()));
            sp.setPostName(objects[1].toString());
            sp.setPostCode(objects[2].toString());
            postList.add(sp);
        }

        return postList;
    }
}
